package com.ulook.lookplanet.ui.home.login;

import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.ulook.lookplanet.R;
import com.ulook.lookplanet.common.ActivityCode;
import com.ulook.lookplanet.data.model.TUser;
import com.ulook.lookplanet.data.model.Visitor;

/**
 * 登陆活动
 */
public class LoginActivity extends AppCompatActivity{

    private LoginViewModel loginViewModel;
    private boolean isRegister = false;

    private EditText nicknameEditText;
    private EditText usernameEditText;
    private EditText passwordEditText;
    private Button loginButton;
    private Button registerButton;
    private TextView forgetPwText;
    private TextView registerText;
    private TextView loginText;
    private ProgressBar loadingProgressBar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        loginViewModel = new ViewModelProvider(this, new LoginViewModelFactory(getApplication())).get(LoginViewModel.class);

        loginViewModel.getLoginFormState().observe(this, loginFormState -> {
            if (loginFormState == null) {
                return;
            }
            // 表单验证
            loginButton.setEnabled(loginFormState.isDataValid());
            registerButton.setEnabled(loginFormState.isDataValid());
            if (loginFormState.getUsernameError() != null) {
                usernameEditText.setError(getString(loginFormState.getUsernameError()));
            }
            if (loginFormState.getPasswordError() != null) {
                passwordEditText.setError(getString(loginFormState.getPasswordError()));
            }
            if(loginFormState.getNicknameError() != null) {
                nicknameEditText.setError(getString(loginFormState.getNicknameError()));
            }
        });

        loginViewModel.getLoginResult().observe(this, loginResult -> {
            if (loginResult == null) {
                return;
            }
            loadingProgressBar.setVisibility(View.GONE);
            if (loginResult.getError() != null) {
                loadingProgressBar.setVisibility(View.GONE);
                showLoginFailed(loginResult.getError());
            }
            if (loginResult.getSuccess() != null) {
                updateUiWithUser(loginResult.getSuccess());
                Intent intent = new Intent();
                intent.putExtra("user", loginResult.getSuccess());
                setResult(ActivityCode.LOGIN_RESULT_OK, intent);
                //成功后完成并销毁登录活动
                finish();
            }

        });

        initPage();

        // 文本输入改变事件监听器
        TextWatcher afterTextChangedListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override
            public void afterTextChanged(Editable s) {
                loginViewModel.loginDataChanged(usernameEditText.getText().toString(),
                                                passwordEditText.getText().toString(),
                                                nicknameEditText.getText().toString());
            }
        };
        // 输入框添加事件监听事件
        usernameEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.addTextChangedListener(afterTextChangedListener);
        // 监听回车键
        passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    loginViewModel.login(usernameEditText.getText().toString(), passwordEditText.getText().toString());
                }
                return false;
            }
        });
        // 监听登陆按钮
        loginButton.setOnClickListener(v -> {
            loadingProgressBar.setVisibility(View.VISIBLE);
            loginViewModel.login(usernameEditText.getText().toString(), passwordEditText.getText().toString());
        });
        registerButton.setOnClickListener(v -> {
            loadingProgressBar.setVisibility(View.VISIBLE);
            loginViewModel.register(nicknameEditText.getText().toString(), usernameEditText.getText().toString(), passwordEditText.getText().toString());
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    /**
     * 返回键
     */
    @Override
    public void onBackPressed(){
        Intent intent = new Intent();
        intent.putExtra("user", new Visitor());
        setResult(ActivityCode.LOGIN_RESULT_OK, intent);
        finish();
    }

    /**
     * 初始化页面
     */
    private void initPage(){

        nicknameEditText = findViewById(R.id.login_nickname);
        usernameEditText = findViewById(R.id.username);
        passwordEditText = findViewById(R.id.password);
        loginButton = findViewById(R.id.login);
        registerButton = findViewById(R.id.register_bt);
        forgetPwText = findViewById(R.id.forget_pw);
        registerText = findViewById(R.id.register_text);
        loginText = findViewById(R.id.login_text);
        loadingProgressBar = findViewById(R.id.loading);

        // 显示注册页面
        registerText.setClickable(true);
        registerText.setOnClickListener(v -> {
            isRegister = true;
            changePage();
        });
        // 显示登陆页面
        loginText.setClickable(true);
        loginText.setOnClickListener(v -> {
            isRegister = false;
            changePage();
        });
        // 忘记密码
        forgetPwText.setClickable(true);
    }

    /**
     * 登陆 or 注册
     */
    private void changePage(){
        if(!isRegister){
            nicknameEditText.setVisibility(View.INVISIBLE);
            registerButton.setVisibility(View.GONE);
            registerText.setVisibility(View.VISIBLE);
            forgetPwText.setVisibility(View.VISIBLE);
            loginButton.setVisibility(View.VISIBLE);
            loginText.setVisibility(View.GONE);
        }else {
            nicknameEditText.setVisibility(View.VISIBLE);
            registerButton.setVisibility(View.VISIBLE);
            registerText.setVisibility(View.GONE);
            forgetPwText.setVisibility(View.GONE);
            loginButton.setVisibility(View.GONE);
            loginText.setVisibility(View.VISIBLE);
        }
    }

    private void updateUiWithUser(TUser user) {
        String welcome = getString(R.string.welcome) + user.getName();
        // TODO 启动成功登录体验
        Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
    }

    private void showLoginFailed(String errorString) {
        Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
    }

}